package com.example.statistics.net.callback

import android.app.Activity
import com.jhj.httplibrary.callback.JsonHttpCallback
import org.jetbrains.anko.toast
import org.json.JSONObject

abstract class BaseHttpCallback<T>(activity: Activity) : JsonHttpCallback<T>(activity) {


    open val mIsOnFailureFinish = false
    open val mIsOnFailureToast = true
    open val mIsOnSuccessToast = false

    override fun parseJson(str: String, resultType: ResultType) {
        val jsonObject = JSONObject(str)
        if (jsonObject.has("code") && jsonObject.has("message")) {
            val msg = jsonObject.getString("message")
            val code = jsonObject.getInt("code")
            when (code) {
                200 -> {
                    if (mIsOnSuccessToast && msg.isNotEmpty()) mActivity.toast(msg)
                }
                else -> {
                    if (mIsOnFailureToast) mActivity.toast(msg)
                    if (mIsOnFailureFinish) mActivity.finish()
                }
            }
        }
        super.parseJson(str, resultType)
    }

    override fun onFailure(msg: String) {
        if (mIsOnFailureToast) mActivity.toast(msg)
        if (mIsOnFailureFinish) mActivity.finish()
    }
}